﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections.Generic;

using Microsoft.AspNetCore.Mvc;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Admin.Services;
using ZhonTai.DynamicApi;
using ZhonTai.Industry.Domain.StationFeature;
using ZhonTai.Industry.Services.StationFeature.Dto.Output;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Industry.Services.StationFeature.Dto.Input;
using ZhonTai.Industry.Services.WorkStation.Dto.Input;
using ZhonTai.Industry.Services.WorkStation.Dto.Output;
using ZhonTai.Admin.Tools.Cache;

namespace ZhonTai.Industry.Services.StationFeature
{
    /// <summary>
    /// 工站功能服务
    /// </summary>
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class StationFeatureService : BaseService, IStationFeatureService, IDynamicApi
    {
        private readonly IStationFeatureRepository _stationFeatureRepository;
        private readonly ICacheTool _cacheTool;

        public StationFeatureService(ICacheTool cacheTool, IStationFeatureRepository stationFeatureRepository)
        {
            _cacheTool = cacheTool;
            _stationFeatureRepository = stationFeatureRepository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<StationFeatureGetOutput> GetAsync(long id)
        {
            var output = await _stationFeatureRepository.GetAsync<StationFeatureGetOutput>(id);
            return output;
        }

        /// <summary>
        /// 查询工站Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<StationFeatureGetOutput> GetStationAsync(long id)
        {
            var output = await _stationFeatureRepository.Select
        .ToOneAsync(a => new StationFeatureGetOutput
        {
            WorkStationIds = _stationFeatureRepository.Where(b => b.FeatureId == id).OrderBy(a => a.Id).ToList(b => b.WorkStation.Id)
        });
            return output;
        }

        /// <summary>
        /// 查询工位功能
        /// </summary>
        /// <param name="wsStatusGetListInput"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<StationFeatureGetListOutput>> GetListAsync(StationFeatureGetListInput wsStatusGetListInput)
        {
            return await _stationFeatureRepository.Select.
                WhereIf(wsStatusGetListInput.WorkStationId != null,
                x => x.StationId.Equals(wsStatusGetListInput.WorkStationId))
                .OrderBy(o => o.Sort)
                .ToListAsync<StationFeatureGetListOutput>();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<StationFeatureGetPageOutput>> GetPageAsync(PageInput<StationFeatureGetPageInput> input)
        {
            var filter = input.Filter;
            var select = _stationFeatureRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                .WhereIf(filter.FeatureId.HasValue && filter.FeatureId > 0, w => w.FeatureId == filter.FeatureId)
                .Include(i => i.WorkStation)
                .Include(i => i.Feature)
                .Count(out var total);
            if (input.SortList != null && input.SortList.Count > 0)
            {
                input.SortList.ForEach(sort =>
                {
                    select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                });
            }
            else
            {
                select = select.OrderBy(a => a.Sort);
            }
            var list = await select
                .Page(input.CurrentPage, input.PageSize)
                .ToListAsync(t =>
                new StationFeatureGetPageOutput
                {
                    StationCode = t.WorkStation.StationCode,
                    LineCode = t.WorkStation.ProductionLine.LineCode,
                    FeatureName = t.Feature.Description
                });
            //关联查询代码

            var data = new PageOutput<StationFeatureGetPageOutput> { List = list, Total = total };

            return data;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(StationFeatureAddInput input)
        {
            if (input != null && input.WorkStationIds.Any())
            {
                // 先获取所有已存在的 StationId 和 FeatureId 组合
                var existingStationFeatures = await _stationFeatureRepository.Select
                    .Where(a => input.WorkStationIds.Contains(a.StationId) && a.FeatureId == input.FeatureId)
                    .ToListAsync();

                // 获取已经存在的 StationId 列表
                var existingStationIds = existingStationFeatures.Select(e => e.StationId).ToHashSet();

                // 过滤掉已经存在的记录，只插入新的记录
                var stationFeatures = input.WorkStationIds
                    .Where(s => !existingStationIds.Contains(s))  // 排除已经存在的 StationId
                    .Select(s => new StationFeatureEntity
                    {
                        StationId = s,
                        FeatureId = input.FeatureId,
                        Enabled = true
                    })
                    .ToList();

                // 如果有新数据需要插入
                if (stationFeatures.Any())
                {
                    var result = await _stationFeatureRepository.InsertAsync(stationFeatures);
                    return result.Last().Id;  // 返回最后插入的 ID
                }
            }
            return -1;  // 如果没有新数据需要插入，返回 -1
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(StationFeatureUpdateInput input)
        {
            var entity = await _stationFeatureRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("工站配置不存在！");
            }

            Mapper.Map(input, entity);
            await _stationFeatureRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await _stationFeatureRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await _stationFeatureRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await _stationFeatureRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetEnableAsync(StationFeatureSetEnableInput input)
        {
            var entity = await _stationFeatureRepository.GetAsync(input.StationFeatureId);
            if (entity.FeatureId == 60000000000002)
            {
                await _cacheTool.SetAsync(CacheKey.VerifyStatus + entity.StationId, input.Enabled);
            }
            entity.Enabled = input.Enabled;
            await _stationFeatureRepository.UpdateAsync(entity);
        }
    }
}